import { useState, useEffect, useMemo } from 'react'
import { Progress, Row, Col, Card, List } from 'antd'
import dayjs from 'dayjs'
import 'antd/dist/antd.css';
import './style.scss'
import xiaoHeLi from '../../assets/xiaoHeLi.gif'
import lvKongLong from '../../assets/绿恐龙.jpg'
import faDianJi from '../../assets/手摇发电机.jpg'
import { red, green } from '@ant-design/colors';
// import leGao from 'https://cbu01.alicdn.com/img/ibank/2019/442/777/10434777244_612855683.jpg'

/* 需求说明
    进入页面，每1秒刷新一次时间，显示当前时间并判断是否过了签到时间。
    执行一次从localStorage读取数据，以显示是否可签到、签到天数等信息。
    可以签到的判断：时间未过且今天还未签到。
    点击签到按钮，存入当前时间数据到localStorage，并从中再次读取。
*/
// 模拟数据
/* const mock = () => {
  const mockData = [
    {
      date: '22-09-26',
      time: '07:24:05'
    }, {
      date: '22-09-27',
      time: '07:24:35'
    }, {
      date: '22-09-29',
      time: '07:27:10'
    }, {
      date: '22-09-30',
      time: '07:23:01'
    }
  ]
  localStorage.setItem('signInData', JSON.stringify(mockData))
} */

const rewards = [{
  name: '大颗粒机械造型玩具',
  img: xiaoHeLi,
  score: 60,
  done: true
}, {
  name: '绿恐龙阿洛',
  img: lvKongLong,
  score: 80,
}, {
  name: '乐高大颗粒积木',
  img: 'https://cbu01.alicdn.com/img/ibank/2019/442/777/10434777244_612855683.jpg',
  score: 100,
}, {
  name: '手摇发电机',
  img: faDianJi,
  score: 60,
}, {
  name: '电动滚珠轨道',
  img: 'https://img.alicdn.com/imgextra/i4/2213943614974/O1CN019aoG241mc8oAuyDBP_!!2213943614974.jpg',
  score: 100,
}, {
  name: '行星轮万年历',
  img: 'https://img.alicdn.com/imgextra/i3/2481485179/O1CN01IHEJGt1o81tAPf3xq_!!2481485179.jpg',
  score: 80,
}, {
  name: '多彩套圈圈',
  img: 'https://gw.alicdn.com/bao/uploaded/i1/3937219703/O1CN01YBHKe62LY1s2mAsU1_!!3937219703.jpg_Q75.jpg_.webp',
  score: 40,
}, {
  name: '弹射笔一支',
  img: 'https://cbu01.alicdn.com/img/ibank/O1CN01VAvs2v1OknUoNTAQh_!!4070161744-0-cib.jpg',
  score: 40,
}, {
  name: '摔扁还原水球',
  img: 'https://gd3.alicdn.com/imgextra/i3/3193757037/O1CN01mzIu8C21qzhhQX83O_!!3193757037.jpg',
  score: 40,
}, {
  name: '5x5数字华容道',
  img: 'https://img.alicdn.com/imgextra/i1/2207662696376/O1CN01SYJKFT1wyG9oh6wfV_!!2207662696376.jpg',
  score: 60,
}, {
  name: '无脸男挂件',
  img: 'https://gd1.alicdn.com/imgextra/i1/0/O1CN01qlfgkS1JBvFNTmqKJ_!!0-item_pic.jpg',
  score: 50,
}, {
  name: '2根变色激光剑',
  img: 'https://gd4.alicdn.com/imgextra/i4/919754628/O1CN01Xt2xWD1k3fofZGA7M_!!919754628.jpg_400x400.jpg',
  score: 60,
}, {
  name: '打不倒的魔术小人',
  img: 'https://img.alicdn.com/imgextra/i3/755233023/O1CN01lWnSGy1YCa3PFgwdw_!!755233023.jpg',
  score: 60,
}, {
  name: '10N弹簧测力计',
  img: 'https://img.alicdn.com/imgextra/i2/719820549/O1CN011FvTtqnDWqgV6rh_!!719820549.jpg',
  score: 60,
}, {
  name: '便携式小型弹簧秤',
  img: 'https://img.alicdn.com/imgextra/i2/2201483592438/O1CN01uE2TWD1TseHpXD5GR_!!2201483592438.jpg',
  score: 80,
}, {
  name: '手动滚珠双轨道',
  img: 'https://gd4.alicdn.com/imgextra/i3/2213943614974/O1CN01C9mWBs1mc8nahJN4G_!!2213943614974.jpg_400x400.jpg',
  score: 100,
}, {
  name: '漂浮记号笔',
  img: 'https://img.alicdn.com/imgextra/i3/2200780947358/O1CN01iEms5j24E0zTr0AS4_!!2200780947358.jpg',
  score: 60,
}, {
  name: '悬浮感叹号',
  img: 'https://img.alicdn.com/imgextra/i3/2248121035/O1CN01fV7fGj1JW4gNbPxpf_!!2248121035.jpg',
  score: 40,
}, {
  name: '未解锁',
  img: 'https://ts1.cn.mm.bing.net/th/id/R-C.d73f591876a3c517b9b6e4639f2da2c7?rik=IdXgOznlC8%2bgQg&riu=http%3a%2f%2fpic.52112.com%2f180713%2fJPG-180713_4%2fKHkf1Yr97p_small.jpg&ehk=pfjytHPuyjlHszOrqY66QEMvE9UdvEIcK6fnGAjWbc0%3d&risl=&pid=ImgRaw&r=0',
  score: 100,
}]

const targets = [{
  text: '读一遍脉药口诀',
  score: 10
}, {
  text: '背诵完脉药口诀',
  score: 20
}, {
  text: '背诵乘法口诀',
  score: 20
}, {
  text: '独立完成一次三项式',
  score: 10,
  done: true,
  time: '22-11-20 12:00:00'
}, {
  text: '小河狸5个项目中，任何一个拆掉后自己不看图能拼起来',
  score: 10
}, {
  text: '学会独立弹奏《小星星》，不出错',
  score: 10
}, {
  text: '连续拍球100个',
  score: 10
}, {
  text: '看错奖励项目完成三项式,安慰奖励',
  score: 5,
  done: true,
  time: '23-8-13 19:00:00'
}, {
  text: '数数签到后表情有几种',
  score: 10,
}, {
  text: '数数没签上到的表情有几种',
  score: 10,
}, {
  text: '拼音电梯考试通过：单韵母',
  score: 5,
  done: true,
  time: '最后更新：24-1-9'
}]

// 平时7:20，周六日8:00
let clock = '07:25:00'
let day = new Date().getDay()
if (day === 0 || day === 6) {
  clock = '08:00:00'
}
// clock = '08:00:00' // 过年过节
const 高兴的字符表情 = rdm(['O(∩_∩)O', '╰(*°▽°*)╯', '(*￣3￣)╭', ' o(￣▽￣)ｄ', '♪(^∇^*)', 'ㄟ(≧◇≦)ㄏ', ' (＾－＾)V', ' ︿(￣︶￣)︿', '(((o(*ﾟ▽ﾟ*)o)))', 'o(*￣▽￣*)o'])
const 不高兴的字符表情 = rdm(['┭┮﹏┭┮', '～>_<～', 'o(╥﹏╥) ', ' (；′⌒`)', ' X﹏X', '（┬_┬）', '（>﹏<）', '（（‵□′））', '<(￣3￣)>', ' (￣△￣；)'])
export default function Home() {
  const [now, setNow] = useState()
  const [data, setData] = useState([])
  const [hasSignIn, seHasSignIn] = useState(false)
  const [isLate, seIsLate] = useState(false)

  useEffect(() => {
    // mock()
    const init = () => {
      const _now = new Date()
      setNow(dayjs(_now).format('HH:mm:ss'))
      // 是否过点
      const h = _now.getHours()
      const m = _now.getMinutes()
      const s = _now.getSeconds()
      const arr = clock.split(':')
      if (h * 3600 + m * 60 + s >= arr[0] * 3600 + arr[1] * 60 + (arr[2] - 0)) {
        seIsLate(true)
      }
    }
    init()
    const timer = setInterval(init, 1000)
    // 今天是否已签到
    const _data = JSON.parse(localStorage.getItem('signInData') || '[]')
    const lastDate = _data?.length && _data.at(-1).date.split('-')
    if (lastDate) {
      const _now = new Date()
      const year = (_now.getFullYear() + '').slice(2)
      const month = (_now.getMonth() + 1 + '').padStart(2, '0')
      const date = (_now.getDate() + '').padStart(2, '0')
      seHasSignIn(lastDate && year === lastDate[0] && month === lastDate[1] && date === lastDate[2])
    }

    return () => clearInterval(timer)
  }, [])

  useEffect(() => {
    setData(JSON.parse(localStorage.getItem('signInData') || '[]'))
  }, [hasSignIn])

  const addScore = () => {
    document.querySelector('.signIn .btn').classList.add('addScore')
  }
  // 签到动作
  const signIn = () => {
    const t = dayjs(new Date())
    const _data = [...data,
    {
      date: t.format('YY-MM-DD'),
      time: t.format('HH:mm:ss')
    }]
    seHasSignIn(true)
    localStorage.setItem('signInData', JSON.stringify(_data))
    addScore()
    alert('你可算来了，加油！明天再来^_^')
  }

  // 连续签到天数计算逻辑：
  // 如果今天还没签到但过了时间，则为0
  // 否则从最后一条数据往前算
  //    如果签了到，最后一条数据是今天，
  //    否则最后一条数据是昨天
  const continuousDays = useMemo(() => {
    let days = 0
    const getContinuousDays = (day) => {
      let nowDay = dayjs(new Date())
      if (day === 'yesterday') {
        nowDay = nowDay.subtract(1, 'day')
      }
      const _data = data.slice().reverse()
      for (let i = 0; i < _data.length; i++) {
        // console.log('~~log', nowDay.subtract(i, 'day').format('YY-MM-DD'))
        if (nowDay.subtract(i, 'day').format('YY-MM-DD') === _data[i].date) {
          days = i + 1
        } else {
          break
        }
      }
    }
    if (!(isLate && !hasSignIn)) {
      getContinuousDays(hasSignIn || 'yesterday')
    }
    return days
  }, [data, isLate, hasSignIn])

  const signInScore = data.length * 5;
  const targetsScore = targets.filter(item => item.done).reduce((pre, next) => pre + next.score, 0)
  // const leftOver = 85
  // 2023-07-07 丢失本次存储数据，重新计算
  // 2023-11-12 服务器到期错过打卡，补偿一次
  const leftOver = 455
  const totalScore = signInScore + targetsScore + leftOver

  let restTotalScore = totalScore
  let notBegin = false
  rewards.forEach(item => {
    if (notBegin) {
      return
    }
    if (restTotalScore < item.score) {
      item.status = 'doing'
      notBegin = true
    } else {
      item.status = 'done'
      restTotalScore -= item.score
    }
  })
  return (
    <div className='p-home'>
      <header>
        <h1>映杰宝宝的主页</h1>
      </header>
      <main>
        <section>
          <article className='scoreList card'>
            <List
              header={<h4>积分</h4>}
              bordered
              size="small"
              dataSource={[
                <>连续签到：<strong>{continuousDays}</strong>天</>,
                <>累积签到：<strong>{data.length}</strong>天</>,
                <>总积分：<strong>{totalScore}</strong>分(之前剩余{leftOver})</>,
              ]}
              renderItem={(item) => <List.Item>{item}</List.Item>}
            />
            <List
              header={<h4>小目标</h4>}
              bordered
              size="small"
              dataSource={[
                <>每天签到：<strong>+5</strong>分</>,
                ...targets.filter(item => !item.done).map(item =>
                  <span key={item.text}>{item.text}：<strong>+{item.score}</strong>分</span>
                ),
              ]}
              renderItem={(item) =>
                <List.Item>{item}</List.Item>
              }
            />
            <List
              header={<h4>已完成</h4>}
              bordered
              size="small"
              dataSource={[
                <>每天签到：<strong>+5</strong>分</>,
                ...targets.filter(item => item.done).map(item =>
                  <span key={item.text}>{item.text}：<strong>+{item.score}</strong>分</span>
                ),
              ]}
              renderItem={(item) => <List.Item>{item}</List.Item>}
            />
          </article>

          <article className='reward card'>
            <h3>奖励</h3>
            <Row gutter={16}>
              {rewards.map(item =>
                <Col span={12} key={item.name}>
                  <Card title={item.name}
                    bordered={false}
                  >
                    <div className='img' style={{ backgroundImage: `url(${item.img})` }} />
                    <div>
                      <strong className='score'>{item.score}</strong>分，
                      {item.status === 'done'
                        ? '已完成(*￣︶￣)'
                        : item.status === 'doing'
                          ? `签到${(item.score - restTotalScore) / 5
                          }天即可获得！`
                          : ''
                      }</div>

                    <Progress
                      percent={item.status === 'done'
                        ? 100
                        : item.status === 'doing'
                          ? restTotalScore * 100 / item.score
                          : 0}

                      status="active"
                      format={percent => ''}
                      steps={item.score / 5}
                      strokeColor={item.status === 'done' ? green[6] : 'default'}
                    />
                  </Card>
                </Col>
              )}
            </Row>
          </article>
        </section>

        <section className='signInBox'>
          <strong>{now}</strong>
          {hasSignIn
            ? <div>今天已经签到了，明天再来吧 {高兴的字符表情}</div>
            : isLate && <div>今天已经晚了，明天再来吧 {不高兴的字符表情}</div>
          }
          <article className={'signIn ' + (isLate || hasSignIn ? 'disable' : '')} onClick={signIn}>
            <span className='btn'>签到</span>
          </article>
          今日签到时间截止：{clock}
        </section>

        <section >
          <article className='history card'>
            <h3>历史记录</h3>
            <ul>{targets.filter(item => item.done).map(item =>
              <li key={item.text}>
                <strong className='score'>+{item.score} </strong>
                <span className='type'>{item.text} - </span>
                <time>{item.time}</time>
              </li>
            )}
              {data?.slice().reverse().map(item =>
                <li key={item.date + item.time}>
                  <strong className='score'>+5 </strong>
                  <span className='type'>每日签到</span>
                  <time>{item.date} {item.time}</time>
                </li>
              )}
            </ul>
          </article>

          <article className='goto card'>
            <h3>去哪里呀</h3>
            <ul>
              <li><a href='http://e-art.top/aluoshizi/' target='_blank'>阿洛识字</a></li>
              <li><a href='http://e-art.top/parkingLot/' target='_blank'>抬杆落杆</a></li>
              <li><a href='http://e-art.top/projects/dian-ti-shi-zi/' target='_blank'>电梯识字</a></li>
              <li><a href='https://mp.weixin.qq.com/s/GB1PLvthY-1dfG5Bv9-WWg' target='_blank'>动画数学</a></li>
              <li><a href='https://www.bilibili.com/video/BV18J411P7ow/' target='_blank'>千与千寻中文版</a></li>
              <li><a href='https://www.bilibili.com/video/BV1CU4y1p7qi?p=1&vd_source=6a104414e02387bfa33c438c7cb9366d' target='_blank'>迪迪狗的一天</a></li>
              {/* <li><a href='' target='_blank'>巨大的起落杆</a></li> */}
              <li><a href='http://e-art.top/cuboid/' target='_blank'>立方体盒子</a></li>
              <li><a href='http://e-art.top/t/cd/UI5/' target='_blank'>探索</a></li>
              <li><a href='http://e-art.top/' target='_blank'>爸爸的博客</a></li>
              <li><a href='https://map.baidu.com/' target='_blank'>百度地图</a></li>
              <li><a href='https://wind-map.gosur.com/cn/' target='_blank'>实时风速</a></li>
              <li><a href='http://du.hanyupinyin.cn/' target='_blank'>汉语拼音</a></li>
              <li><a href='https://echarts.apache.org/examples/zh/editor.html?c=scatter-life-expectancy-timeline' target='_blank'>各国人均寿命与GDP关系演变</a></li>
              <li><a href='https://www.bilibili.com/video/BV1gT4y1m7ec/' target='_blank'>八段锦（呼吸口令）</a></li>
              <li><a href='https://giza.mused.org/zh-hans/guided/335/da-jin-zi-ta-nei-bu' target='_blank'>漫游金字塔内部</a></li>
              <li><a href='http://species-in-pieces.com/' target='_blank'>30种动物的碎片变化</a></li>
            </ul>
          </article>
        </section>
      </main>
    </div>
  )
}

function rdm(arr) {
  const ret = arr[Math.floor(arr.length * Math.random())]
  console.log('~~ret', ret)
  return ret
}

// 2023-11-12 备份打卡数据
const signInData = [
  {
    "date": "23-07-09",
    "time": "07:55:41"
  },
  {
    "date": "23-08-15",
    "time": "06:28:00"
  },
  {
    "date": "23-08-17",
    "time": "07:55:08"
  },
  {
    "date": "23-08-28",
    "time": "07:29:00"
  },
  {
    "date": "23-08-29",
    "time": "07:26:33"
  },
  {
    "date": "23-09-02",
    "time": "07:58:40"
  },
  {
    "date": "23-09-04",
    "time": "07:17:55"
  },
  {
    "date": "23-09-06",
    "time": "07:19:43"
  },
  {
    "date": "23-09-07",
    "time": "07:19:38"
  },
  {
    "date": "23-09-14",
    "time": "07:19:27"
  },
  {
    "date": "23-09-15",
    "time": "07:18:40"
  },
  {
    "date": "23-09-23",
    "time": "07:50:10"
  },
  {
    "date": "23-09-24",
    "time": "07:43:25"
  },
  {
    "date": "23-10-01",
    "time": "07:58:57"
  },
  {
    "date": "23-10-08",
    "time": "07:19:58"
  },
  {
    "date": "23-10-13",
    "time": "07:18:50"
  },
  {
    "date": "23-10-15",
    "time": "07:47:35"
  },
  {
    "date": "23-10-20",
    "time": "07:08:32"
  },
  {
    "date": "23-10-22",
    "time": "07:26:21"
  },
  {
    "date": "23-11-02",
    "time": "07:15:54"
  },
  {
    "date": "23-11-04",
    "time": "07:58:13"
  }
]